<template>
  <div class="scrollTop" @click="top" v-show="isShow">
    <img src="../assets/top.png" alt="" />
  </div>
</template>

<script>
export default {
  name: "BackTop",
  data() {
    return {
      isShow: false,
    };
  },
  methods: {
		// 防抖函数
    debounce(func, wait=0) {
      if (typeof func !== "function") {
        throw new TypeError("need a function arguments");
      }
      let timeid = null;
      let result;
      return function () {
        let context = this;
        let args = arguments;
        if (timeid) {
          clearTimeout(timeid);
        }
        timeid = setTimeout(function () {
          result = func.apply(context, args);
        }, wait);
				return result;
      }
    },
    top() {
      document.documentElement.scrollTop = document.body.scrollTop = 0;
    },
    handleScroll() {
      if (window.pageYOffset > 500) {
        this.isShow = true;
      } else {
        this.isShow = false;
      }
    },
  },

  mounted() {
    window.addEventListener("scroll", this.debounce(this.handleScroll, 500));
  },
};
</script>

<style scoped>
.scrollTop {
  position: fixed;
  right: 8px;
  bottom: 55px;
}
.scrollTop img {
  width: 47px;
  height: 47px;
}
</style>